package com.learn.project2.service.wx.order;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.learn.project2.bean.*;
import com.learn.project2.mapper.*;
import com.learn.project2.model.bo.wx.order.OrderCommentBO2;
import com.learn.project2.model.bo.wx.order.OrderSubmitBO;
import com.learn.project2.model.vo.wx.order.OrderDetailVO2;
import com.learn.project2.model.vo.wx.order.OrderListVO2;
import com.sun.corba.se.spi.ior.IdentifiableFactoryFinder;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.omg.CORBA.ORB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhizhuke
 * @version 1.0
 * @description:
 * @date 2022-01-08 15-59
 */
@Service
public class OrderServiceImpl2 implements OrderService2 {

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketOrderChannelMapper orderChannelMapper;
    @Autowired
    MarketUserMapper userMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketSystemMapper systemMapper;


    /**
     * @description:
     * @param:
     * @return:
     * @author zhizhuke
     * @date: 2022-01-08 16:21
     */
    @Override
    public void confirm(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 401);
        Date time = new Date();
        marketOrder.setConfirmTime(time);
        marketOrder.setUpdateTime(time);
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author zhizhuke
     * @date: 2022-01-11 08:44
     */
    @Override
    public void delete(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setDeleted(true);
        orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author zhizhuke
     * @date: 2022-01-11 09:54
     */
    @Override
    public void refund(Integer orderId) {

        MarketOrder o = orderMapper.selectByPrimaryKey(orderId);
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        order.setOrderStatus(((short) 202));
        order.setRefundAmount(o.getActualPrice().intValue());//todo 暂定为实际付款价格，退款策略未知
        order.setRefundType("ref");//todo 退款方式写死，因为不知道退款方式有哪些
        order.setRefundContent("zhen");//todo 退款备注未知，暂写死
        Date refundTime = new Date();
        order.setRefundTime(refundTime);
        order.setUpdateTime(refundTime);
        orderMapper.updateByPrimaryKeySelective(order);

    }

    @Override
    /**
     * @description: 新建商品评论
     * @author wangzhuo
     * @date 2022-01-10 16:50
     * @version 1.0
     */
    public int setComment(OrderCommentBO2 orderCommentBO2) {
        MarketComment marketComment = new MarketComment();

        //1.根据orderGoodsId在market_order_goods表中主键查询goods_id和order_id
        MarketOrderGoods marketOrderGoods = orderGoodsMapper.selectByPrimaryKey(orderCommentBO2.getOrderGoodsId());
        Integer goodsId = marketOrderGoods.getGoodsId();
        Integer orderId = marketOrderGoods.getOrderId();
        //2.通过order_id 在market_order表中主键查询user_id
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        Integer userId = marketOrder.getUserId();
        //valueId 就是goodsId
        marketComment.setValueId(goodsId);
        marketComment.setType((byte) 0);
        marketComment.setContent(orderCommentBO2.getContent());
        marketComment.setUserId(userId);
        marketComment.setHasPicture(orderCommentBO2.getHasPicture());
        if (orderCommentBO2.getHasPicture() == true) {
            marketComment.setPicUrls(orderCommentBO2.getPicUrls());
        }
        marketComment.setStar(orderCommentBO2.getStar());
        marketComment.setAddTime(new Date());
        marketComment.setUpdateTime(new Date());
        marketComment.setDeleted(false);
        int insert = commentMapper.insert(marketComment);
        //获取添加的订单评论 id.加到,market_order_goods表中
        int orderCommentId = marketComment.getId();
        MarketOrderGoods marketOrderGoods1 = new MarketOrderGoods();
        marketOrderGoods1.setComment(orderCommentId);
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderGoodsExampleCriteria = orderGoodsExample.createCriteria();
        orderGoodsExampleCriteria.andIdEqualTo(orderCommentBO2.getOrderGoodsId());
        int i = orderGoodsMapper.updateByExampleSelective(marketOrderGoods1, orderGoodsExample);
        Short comments = marketOrder.getComments();
        if (i != 0 && comments > 0) {
            //评论成功后,market_order表中comments数据减1
            MarketOrder marketOrder1 = new MarketOrder();
            marketOrder1.setComments((short) (comments - 1));
            MarketOrderExample orderExample = new MarketOrderExample();
            MarketOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andIdEqualTo(orderId);
            orderMapper.updateByExampleSelective(marketOrder1, orderExample);
        }

        if (insert == 1) {
            return 200;
        }
        return 400;
    }

    @Override
    /**
     * @description:
     * @author wangzhuo
     * @date 2022-01-10 20:52
     * @version 1.0
     */
    public void cancel(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        /**
         * const statusMap = {
         *   101: '未付款',
         *   102: '用户取消',
         *   103: '系统取消',
         *   201: '已付款',
         *   202: '申请退款',
         *   203: '已退款',
         *   301: '已发货',
         *   401: '用户收货',
         *   402: '系统收货'
         * }
         */
        marketOrder.setOrderStatus((short) 102);
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int i = orderMapper.updateByExampleSelective(marketOrder, orderExample);
    }

    @Override
    /**
     * @description:
     * @author wangzhuo
     * @date 2022-01-11 09:03
     * @version 1.0
     */
    public OrderDetailVO2 getDetail(Integer orderId) {

        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        OrderDetailVO2.OrderInfoBean orderInfoBean = new OrderDetailVO2.OrderInfoBean();
        orderInfoBean.setConsignee(marketOrder.getConsignee());  //收货人名称
        orderInfoBean.setAddress(marketOrder.getAddress());   //收货具体地址
        if (marketOrder.getAddTime() != null) {
            orderInfoBean.setAddTime(marketOrder.getAddTime().toString());
        }
        orderInfoBean.setOrderSn(marketOrder.getOrderSn()); //订单编号
        orderInfoBean.setActualPrice(marketOrder.getActualPrice());
        orderInfoBean.setMobile(marketOrder.getMobile());
        orderInfoBean.setMessage(marketOrder.getMessage());

        if (marketOrder.getOrderStatus() == 101) {
            orderInfoBean.setOrderStatusText("未付款");
        } else if (marketOrder.getOrderStatus() == 102) {
            orderInfoBean.setOrderStatusText("用户取消");
        } else if (marketOrder.getOrderStatus() == 103) {
            orderInfoBean.setOrderStatusText("系统取消");
        } else if (marketOrder.getOrderStatus() == 201) {
            orderInfoBean.setOrderStatusText("已付款");
        } else if (marketOrder.getOrderStatus() == 202) {
            orderInfoBean.setOrderStatusText("申请退款");
        } else if (marketOrder.getOrderStatus() == 203) {
            orderInfoBean.setOrderStatusText("已退款");
        } else if (marketOrder.getOrderStatus() == 301) {
            orderInfoBean.setOrderStatusText("已发货");
        } else if (marketOrder.getOrderStatus() == 401) {
            orderInfoBean.setOrderStatusText("用户收货");
        } else if (marketOrder.getOrderStatus() == 402) {
            orderInfoBean.setOrderStatusText("系统收货");
        }
        orderInfoBean.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderInfoBean.setGoodsPrice(marketOrder.getGoodsPrice());
        //未付款状态，没有三条exp信息
        if (marketOrder.getShipChannel() != null) {
            orderInfoBean.setExpName(marketOrder.getShipChannel());  //发货快递公司
        }
        if (marketOrder.getShipChannel() != null) {
            //如果快递公司数据存在，用name在market_order_channel表中查找对应的code
            MarketOrderChannelExample orderChannelExample = new MarketOrderChannelExample();
            MarketOrderChannelExample.Criteria criteria = orderChannelExample.createCriteria();
            criteria.andNameEqualTo(marketOrder.getShipChannel());
            List<MarketOrderChannel> marketOrderChannels = orderChannelMapper.selectByExample(orderChannelExample);
            for (MarketOrderChannel marketOrderChannel : marketOrderChannels) {
                orderInfoBean.setExpCode(marketOrderChannel.getCode());
            }
        }
        if (marketOrder.getShipSn() != null) {
            orderInfoBean.setExpNo(marketOrder.getShipSn()); //发货编号
        }

        orderInfoBean.setCouponPrice(marketOrder.getCouponPrice()); //优惠券减免
        orderInfoBean.setId(marketOrder.getId());
        orderInfoBean.setFreightPrice(marketOrder.getFreightPrice()); //配送费用
        //获取订单状态信息
        //  未付款 cancle，pay  true
        //  已付款 refund true
        //  待收货 confirm true
        // 待评价  delete，comment，rebuy,aftersale true
        // 已评价  delete,comment,rebuy,aftersale true
        OrderDetailVO2.OrderInfoBean.HandleOptionBean handleOptionBean = new OrderDetailVO2.OrderInfoBean.HandleOptionBean();
        if (marketOrder.getOrderStatus() == 101) { //未付款
            handleOptionBean.setCancel(true);
            handleOptionBean.setPay(true);
        }
        if (marketOrder.getOrderStatus() == 201) {  //已付款
            handleOptionBean.setRefund(true);
        }
        if (marketOrder.getOrderStatus() == 301) { //待发货
            handleOptionBean.setConfirm(true);
        }
        if (marketOrder.getOrderStatus() == 401 || marketOrder.getOrderStatus() == 402) { //待评价
            handleOptionBean.setDelete(true);
            handleOptionBean.setComment(true);
            handleOptionBean.setRebuy(true);
            handleOptionBean.setAftersale(true);
        }
        //orderInfoBean信息插入完成
        orderInfoBean.setHandleOption(handleOptionBean);
        //根据orderId在market_order_goods表中查询所有信息
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        //注意：只需查询delted=0的数据
        criteria.andDeletedEqualTo(false);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        OrderDetailVO2 orderDetailVO2 = new OrderDetailVO2();
        orderDetailVO2.setOrderGoods(marketOrderGoods);
        orderDetailVO2.setOrderInfo(orderInfoBean);
        orderDetailVO2.setExpressInfo(null);// 未找到相关信息
        return orderDetailVO2;
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author zhizhuke
     * @date: 2022-01-10 22:57
     */
    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {

        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        example.createCriteria().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<MarketOrderGoods> goodsList = orderGoodsMapper.selectByExample(example);
        return goodsList.get(0);

    }

    @Override
    /**
     * @description: 根据showType，查询不同的list
     * @author wangzhuo
     * @date 2022-01-11 14:22
     * @version 1.0
     */
    public OrderListVO2 getList(Integer showType, Integer page, Integer limit, String username) {
        //1.根据username在market_user表中查询对应的userId
        MarketUserExample userExample = new MarketUserExample();
        MarketUserExample.Criteria criteria1 = userExample.createCriteria();
        criteria1.andUsernameEqualTo(username);
        //注意：因为只需要一条数据，最好查询delted=0的数据
        criteria1.andDeletedEqualTo(false);
        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        Integer userId = null;
        for (MarketUser marketUser : marketUsers) {
            userId = marketUser.getId();
        }

        short status = 0;
        short status2 = 0;
        String orderStatusText = null;
        if (showType == 1) { //0是未付款
            status = 101;
            orderStatusText = "未付款";
        } else if (showType == 2) { //1是未发货
            status = 201;
            orderStatusText = "未发货";
        } else if (showType == 3) { //2是已发货
            status = 301;
            orderStatusText = "已发货";
        } else if (showType == 4) {  //3是已确认收货(包含用户收货和系统收货)
            status = 401;
            status2 = 402;
            orderStatusText = "已收货";
        }
        //2.分页
        PageHelper.startPage(page, limit);
        //3.根据userId和status在market_order表中查询
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteriaOrder = orderExample.createCriteria();
        //4.已发货分为用户收货与系统收货
        //注意，此处status==0可能会导致NPE
        if (status == 401) {
            criteriaOrder.andOrderStatusBetween(status, status2);
        } else if (status != 0) {
            criteriaOrder.andOrderStatusEqualTo(status);
        }

        if (userId != 0) {
            criteriaOrder.andUserIdEqualTo(userId);
        }
        //注意：只需查询delted=0的数据
        criteriaOrder.andDeletedEqualTo(false);
        List<MarketOrder> marketOrders = orderMapper.selectByExample(orderExample);
        List<OrderListVO2.ListBean> listBeanList = new ArrayList<>();
        for (MarketOrder marketOrder : marketOrders) {
            //5.向listBean中封装数据
            OrderListVO2.ListBean listBean = new OrderListVO2.ListBean();
            String statusText = null;
            //101: '未付款',
            //  102: '用户取消',
            //  103: '系统取消',
            //  201: '已付款',
            //  202: '申请退款',
            //  203: '已退款',
            //  301: '已发货',
            //  401: '用户收货',
            //  402: '系统收货'
            if (marketOrder.getOrderStatus() == 101) {
                statusText = "未付款";
            } else if (marketOrder.getOrderStatus() == 102) {
                statusText = "用户取消";
            } else if (marketOrder.getOrderStatus() == 103) {
                statusText = "系统取消";
            } else if (marketOrder.getOrderStatus() == 201) {
                statusText = "已付款";
            } else if (marketOrder.getOrderStatus() == 202) {
                statusText = "申请退款";
            } else if (marketOrder.getOrderStatus() == 203) {
                statusText = "已退款";
            } else if (marketOrder.getOrderStatus() == 301) {
                statusText = "已发货";
            } else if (marketOrder.getOrderStatus() == 401) {
                statusText = "用户收货";
            } else if (marketOrder.getOrderStatus() == 402) {
                statusText = "系统收货";
            }
            listBean.setOrderStatusText(statusText);
            listBean.setAftersaleStatus(marketOrder.getAftersaleStatus());
            listBean.setIsGroupin(false);//不知道内容，默认false
            listBean.setOrderSn(marketOrder.getOrderSn());
            listBean.setActualPrice(marketOrder.getActualPrice());
            //6.根据orderId在market_order_goods表中查询数据
            MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria criteriaOrderGoods = orderGoodsExample.createCriteria();
            criteriaOrderGoods.andOrderIdEqualTo(marketOrder.getId());
            //注意：只需查询delted=0的数据
            criteriaOrderGoods.andDeletedEqualTo(false);
            List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
            //7.向GoodsListBean中封装数据
            List<OrderListVO2.ListBean.GoodsListBean> goodsListBeans = new ArrayList<>();
            for (MarketOrderGoods orderGood : orderGoods) {
                OrderListVO2.ListBean.GoodsListBean goodsListBean = new OrderListVO2.ListBean.GoodsListBean();
                goodsListBean.setNumber(orderGood.getNumber());
                goodsListBean.setPicUrl(orderGood.getPicUrl());
                goodsListBean.setPrice(orderGood.getPrice());
                goodsListBean.setId(orderGood.getId());
                goodsListBean.setGoodsName(orderGood.getGoodsName());
                goodsListBean.setSpecifications(orderGood.getSpecifications());
                goodsListBeans.add(goodsListBean);
            }
            //8.添加handel参数
            OrderListVO2.ListBean.HandleOptionBean handleOptionBean = new OrderListVO2.ListBean.HandleOptionBean();

            if (status == 102 || status == 103) {
                handleOptionBean.setCancel(true);     //已取消
            }
            handleOptionBean.setDelete(marketOrder.getDeleted());
            if (status >= 201) {
                handleOptionBean.setPay(true);      //已付款
            }
            if (status >= 301) {
                handleOptionBean.setComment(true);   //已发货
            }
            if (status >= 401 || marketOrder.getOrderStatus() >= 402) {
                handleOptionBean.setConfirm(true);   //已收货
            }
            if (status == 203 || marketOrder.getOrderStatus() == 301) {
                handleOptionBean.setRefund(true);     //退款
            }
            handleOptionBean.setRebuy(true);     // TODO 不知道是什么wx-order-detail（王茁）
            if (status != 0) {
                handleOptionBean.setAftersale(true);  //售后
            }
            listBean.setGoodsList(goodsListBeans);
            listBean.setId(marketOrder.getId()); //订单id
            listBean.setHandleOption(handleOptionBean);
            //9.封装到listBeanList中
            listBeanList.add(listBean);
        }
        //10.
        PageInfo<MarketOrder> pageInfo = new PageInfo<>(marketOrders);
        //11.最后封装到VO
        OrderListVO2 orderListVO2 = new OrderListVO2();
        orderListVO2.setTotal((int) pageInfo.getTotal());
        orderListVO2.setPages(pageInfo.getPages());
        orderListVO2.setLimit(limit);
        orderListVO2.setPage(page);
        orderListVO2.setList(listBeanList);
        return orderListVO2;
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author zhizhuke
     * @date: 2022-01-12 09:25
     */
    @Transactional
    @Override
    public void submit(OrderSubmitBO orderSubmitBO) {
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();

        //根据addressId查询收货人信息
        MarketAddress marketAddress = addressMapper.selectByPrimaryKey(orderSubmitBO.getAddressId());
        String consignee = marketAddress.getName();
        String address = marketAddress.getProvince() + marketAddress.getCity() + marketAddress.getCounty() + marketAddress.getAddressDetail();
        String mobile = marketAddress.getTel();





        //根据userId查询商品
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        if (orderSubmitBO.getCartId()!=0){
            //立即购买
            criteria.andIdEqualTo(orderSubmitBO.getCartId());
        }else {
            //购物车购买
            criteria.andUserIdEqualTo(user.getId()).andDeletedEqualTo(false).andCheckedEqualTo(true);
        }
        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);

        BigDecimal goodsPrice = new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            goodsPrice = goodsPrice.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
        }

        //根据couponId 查询
        MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(orderSubmitBO.getCouponId());
        BigDecimal couponPrice = marketCoupon == null ? new BigDecimal(0) : marketCoupon.getDiscount();

        //将优惠券设置为已使用
        if (marketCoupon!=null){
            MarketCouponUser couponUser = new MarketCouponUser();
            couponUser.setId(marketCoupon.getId());
            couponUser.setStatus(((short) 1));
            couponUser.setDeleted(true);
            couponUserMapper.updateByPrimaryKeySelective(couponUser);
        }

        BigDecimal freightPrice = new BigDecimal(0);
        String min = systemMapper.selectValueByName("market_express_freight_min");
        String less = systemMapper.selectValueByName("market_express_freight_value");
        if (goodsPrice.compareTo(new BigDecimal(min)) >= 0){
            freightPrice = new BigDecimal(less);
        }
        BigDecimal intergralPrice = new BigDecimal(0);
        BigDecimal grouponPrice = new BigDecimal(0);
        BigDecimal orderPrice = goodsPrice.add(freightPrice).subtract(couponPrice);
        BigDecimal actualPrice = orderPrice.subtract(intergralPrice);
        if (actualPrice.compareTo(new BigDecimal(0)) < 0){
            actualPrice = new BigDecimal(0);
        }
        Date time = new Date();
        MarketOrder order = new MarketOrder(null, user.getId(), "11", ((short) 101), ((short) 0), consignee, mobile, address, orderSubmitBO.getMessage(),
                goodsPrice, freightPrice, couponPrice, intergralPrice, grouponPrice, orderPrice, actualPrice, new SimpleDateFormat("yyyyMMdd").format(time) + 1,
                time, null, null, null, null, null, null, null, null, ((short) marketCarts.size()), null, time, time, false);

        //往order表中插入数据
        orderMapper.insert(order);


        //更新订单编号
        MarketOrder order1 = new MarketOrder();
        order1.setOrderSn(new SimpleDateFormat("yyyyMMdd").format(time) + order.getId());
        order1.setId(order.getId());
        orderMapper.updateByPrimaryKeySelective(order1);

        //删除购物车里面的指定商品
        for (MarketCart marketCart : marketCarts) {
            cartMapper.updateDeletedByProductIdAndUserId(marketCart.getProductId(), user.getId());

            //增加ordergoods记录
            MarketOrderGoods orderGoods = new MarketOrderGoods(null, order.getId(), marketCart.getGoodsId(), marketCart.getGoodsName(), marketCart.getGoodsSn(),
                    marketCart.getProductId(), marketCart.getNumber(), marketCart.getPrice().doubleValue(), marketCart.getSpecifications(),
                    marketCart.getPicUrl(), 0, order.getAddTime(), order.getUpdateTime(), false);
            orderGoodsMapper.insert(orderGoods);
        }


    }

    @Override
    public void prepay(Integer orderId) {
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        order.setOrderStatus(((short) 201));
        Date time = new Date();
        order.setPayId(new SimpleDateFormat("yyyyMMddHHmmss").format(time));
        order.setPayTime(time);
        order.setUpdateTime(time);

        orderMapper.updateByPrimaryKeySelective(order);
    }
}
